package psicomodelagem

class BaseController {

    def defaultAction = "list"

    def login = {
        session.usuarioId = null
        Usuario usuario = Usuario.autenticar(params.name, params.password)
        if (usuario) {
            session.usuarioId = usuario.id

        }
        else {
            flash.loginNotice = message(code: 'intercept.invalid.login')
        }
        redirect(url: params.url)
    }

    def logout = {
        session.usuarioId = null

        redirect(controller: 'usuario', action: 'list')
    }

    def actionMethods() {
        def methods = null
        switch (actionName) {
            case 'login':
                methods = [ 'POST', 'PUT' ]
                break;
            case 'create':
                methods = [ 'GET' ]
                break;
            case 'delete':
                methods = [ 'POST', 'DELETE' ]
                break;
            case 'update':
            case 'save':
                methods = [ 'POST', 'PUT' ]
                break;
        }
        methods
    }

    def validMethod(acceptable) {
        def method = request.method
        acceptable.find { it == method } ? null : message(code: 'Illegal operation')
    }

    def loggedInUsuario() {
        if (!session.usuarioId) {
            return message(code: 'intercept.not.loggedin')
        }
        null
    }

    Usuario sessionUsuario() {
        if (session.usuarioId) {
            return Usuario.get(session.usuarioId)
        }
        null
    }


    void prepareList() {
        if (!params.max) {
            params.max = 10
        }
        if (!params.order) {
            params.order = "desc"
        }
        if (!params.sort) {
            params.sort = "id"
        }
    }
}